package com.fengpanlong.web;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fengpanlong.entity.Employee;
import com.fengpanlong.service.Validate;
import com.fengpanlong.util.exception.ServiceException;

public class LoginServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String method = request.getMethod();
		if("GET".equalsIgnoreCase(method)) {
			goTojsp(request, response, "login.jsp");
		} else {
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			Employee employee = null;
			try {
				employee = Validate.userIsOK(username, password);
			} catch (ServiceException e) {
				String msg = e.getMessage();
				request.setAttribute("msg", msg);
				goTojsp(request, response, "login.jsp");
				return;
			}
			request.getSession().setAttribute("employee", employee);
			response.sendRedirect("main.jspx");
		}
	}
	/**
	 * 去对应jsp页面
	 * @param request
	 * @param response
	 * @param jspName
	 * @throws ServletException
	 * @throws IOException
	 */
	private void goTojsp(HttpServletRequest request,
			HttpServletResponse response, String jspName) throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/views/" + jspName).forward(request, response);
	}
}
